const cloud = require('wx-server-sdk')
cloud.init({
    env: cloud.DYNAMIC_CURRENT_ENV
})
const dayjs = require('dayjs');
const ACTS = 'cloud-activities';
const GROUP = 'cloud-activities-groups';
const PART = 'cloud-participant';
const BASE = 'cloud-user-base';
const VLOG = 'cloud-vote-log';
const db = cloud.database();
const _ = db.command;

// 云函数入口函数
exports.main = async (event, context) => {
    const wxContext = cloud.getWXContext()
    /**获取当前日期 */
    let nowDate = dayjs().format('YYYY-MM-DD');
    console.log(nowDate)
    /**获取用户openid */
    let openid = event.openid || wxContext.OPENID
    /**获取基础用户信息 */
    let userRes = await db.collection(BASE).where({
        openid
    }).get();
    if (userRes.data.length == 0) {
        return {
            errCode: -1,
            errMsg: '基础用户信息不存在'
        }
    }
    let userData = userRes.data[0];
    /**获取参与信息 */
    //participantId
    let partId = event.partId;
    let partRes = await db.collection(PART).doc(partId).get();
    let partData = partRes.data;
    /**获取当前活动信息 */
    let activityId = partData.activityId;
    let activityRes = await db.collection(ACTS).doc(activityId).get();
    let activityData = activityRes.data;

    /**查询当前活动需要的 */
    let voterId = userData._id;
    let voteRes = null
    voteRes = await db.collection(VLOG).where({
        activityId,
        participantId:partId
    }).get();
    let voteData = voteRes.data
    let canVote = true
    voteData.forEach(function(ele,index){
        if(ele.voterId == voterId){
            canVote = false
        }
    })
    return {
        canVote,
        voteList:voteData
    }
}